package com.lookme.lmtool;

import com.lookme.core.javafx.FxApp;
import com.lookme.core.javafx.helper.FxmlHelper;
import com.lookme.lmtool.model.Env;
import com.lookme.lmtool.utils.EnvUtils;
import com.lookme.lmtool.utils.ToolUtils;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.Optional;

public class CaptchaCrackerMain extends Application {

    public static final String LOGO_PATH = "/images/ocr.png";

    public static final String FXML_PATH = "/fxml/com/lookme/lmtool/CaptchaCrackerRootLayout.fxml";

    public static void main(String[] args) {
        launch(args);
    }

    public static final String TITLE="验证码识别训练工具";
    @Override
    public void start(Stage primaryStage) {
        FxApp.init(primaryStage, LOGO_PATH);
        FxApp.setupIcon(primaryStage);
        EnvUtils.loadSetting();

        primaryStage.setTitle(TITLE);
        primaryStage.setWidth(1224);
        primaryStage.setHeight(800);

        primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>(){
            @Override
            public void handle(WindowEvent event) {
                if(StringUtils.isEmpty(Env.getInstance().getProjectInfo().getPath())) {
                    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                    alert.setTitle("确认退出");
                    alert.setHeaderText("退出前是否保存当前工程？");
                    alert.setContentText("");
                    Optional result = alert.showAndWait();
                    if (result.get() == ButtonType.OK) {
                        File file = ToolUtils.createFileChooser("保存工程").showSaveDialog(FxApp.primaryStage);
                        try {
                            if (file != null) {
                                try {
                                    if (StringUtils.isEmpty(Env.getInstance().getProjectInfo().getPath())) {
                                        Env.getInstance().getProjectInfo().setPath(file.getAbsolutePath());
                                    }
                                } catch (Exception e) {

                                }
                                Env.getInstance().setInitDirectory(file.getParent());
                            }
                        } catch (Exception ex) {
                            System.out.println(ex.getMessage());
                        }
                    }else{
                        return;
                    }
                }
                EnvUtils.saveProject(Env.getInstance().getProjectInfo());
                System.exit(0);
            }
        });
        

        FxmlHelper.loadIntoStage(FXML_PATH, primaryStage).show();
    }


}